package com.wsz.springsecurity03.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wsz.springsecurity03.Exception.KaptchaNotMatchException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

public class LoginKaptchaFilter extends UsernamePasswordAuthenticationFilter {

    private static final String FORM_KAPTCHA_KEY = "kaptcha";

    private String kaptchaParameter = FORM_KAPTCHA_KEY;

    public String getKaptchaParameter() {
        return kaptchaParameter;
    }

    public void setKaptchaParameter(String kaptchaParameter) {
        this.kaptchaParameter = kaptchaParameter;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if ( !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        try {
            Map<String,String> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
            String kaptcha = map.get(this.getKaptchaParameter());
            String username = map.get(this.getKaptchaParameter());
            String password = map.get(this.getPasswordParameter());

            String sessionCode = (String) request.getSession().getAttribute("kaptcha");

            if(!StringUtils.isEmpty(sessionCode) && !StringUtils.isEmpty(kaptcha) && sessionCode.equals(kaptcha)){
                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
                this.setDetails(request, authRequest);
                return this.getAuthenticationManager().authenticate(authRequest);
            }

        }
        catch (IOException e) {
            e.printStackTrace();
        }
        throw new KaptchaNotMatchException("验证码异常");
    }
}
